package com.otitan.forest.right.config;

import com.otitan.forest.right.entity.SysUserEntity;
import com.otitan.forest.right.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Description: java类作用描述
 * @Author: jiachangsen
 * @CreateDate: 2020/08/10 17:12
 * @UpdateUser: jiachangsen
 * @UpdateDate: 2020/08/10 17:12
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class AuthorityHandlerAspect {
    @Pointcut("execution(* com.otitan.forest.right.controller.*.*(..))")
    public void executeService() {
    }

    @Around("executeService()")
    public Object authorityHandler(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();

        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        String methodName = methodSignature.getMethod().getName();
        String declaringTypeName = pjp.getSignature().getDeclaringType().getSimpleName();
        // 获取当前登录用户信息
        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        String realName = "";
        if (sysUserEntity != null) {
            realName = sysUserEntity.getRealName();
        }
        String ipAddr = IpUtil.getIpAddr();

        log.info("【接口调用】## 开始 ## - 【{}】  >>>>>> IP地址【{}】，用户名【{}】，方法名：【{}.{}】",
                start,
                ipAddr,
                realName,
                declaringTypeName,
                methodName);

        Object proceed = pjp.proceed();

        long end = System.currentTimeMillis();

        BigDecimal bigDecimal = new BigDecimal(end - start);
        BigDecimal time = bigDecimal.divide(BigDecimal.valueOf(1000), 3, BigDecimal.ROUND_HALF_UP);
        log.info("【接口调用】## 结束 ## - 【{}】  >>>>>> 耗时：{}s <<<<< ",
                start,
                time);
        return proceed;

    }
}
